package main

import (
	"context"
	"crypto/tls"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"math"
	"math/rand"
	"net"
	"net/http"
	"net/http/httptrace"
	"os"
	"sort"
	"sync"
	"time"

	cloudflare "github.com/cloudflare/cloudflare-go"
	"gonum.org/v1/gonum/stat"
)

type CIDRConfig struct {
	CIDR       string  `json:"cidr"`
	MaxSuccess int64   `json:"max_success"`
	MaxDelay   int64   `json:"max_delay"`
	Delays     []int64 `json:"-"`
}

type CIDRConfigFile struct {
	CIDR       string `json:"cidr"`
	MaxSuccess int64  `json:"max_success"`
	MaxDelay   int64  `json:"max_delay"`
}

type HistoryEntry struct {
	CIDR   string  `json:"cidr"`
	Date   string  `json:"date"`
	Delays []int64 `json:"delays"`
}

// 系统状态统计 - 增强版
type SystemStats struct {
	SuccessRate       float64 // 平均成功率
	DelayAvg          float64 // 平均延迟
	DelayStdDev       float64 // 延迟标准差
	Trend             float64 // 趋势强度
	TrendConfidence   float64 // 趋势置信度
	SeasonalAmplitude float64 // 季节性波动幅度
	OutlierRatio      float64 // 异常值比例
}

// 算法参数集合
type AlgorithmParams struct {
	EWMASmoothingFactor float64 // EWMA平滑因子(α)
	WMAPredictionWindow int     // WMA预测窗口大小
	TrendThreshold      float64 // 趋势阈值
	StressFactorBase    float64 // 基础压力因子
	StressFactorExp     float64 // 压力因子指数
	MinChangeStep       float64 // 最小调整步长
	RoundStep           int64   // 舍入精度
	FloorFactor         float64 // 阈值下限因子
	CeilingFactor       float64 // 阈值上限因子
}

var (
	cidrRanges []CIDRConfig
	// 优选域名SAAS之后的 访问域名
	host = "blog.520613.xyz"
	// 扫描线程
	maxConcurrent = 20

	// 你的CFTokens
	apiToken = "jLnJkkHxr4_EVTD9QZ"
	// 你的主域名
	domain = "cdnss.dpdns.org"
	// 优选域名
	youxuanomain = "*.cdnss.dpdns.org"
	// 优选域名V6
	ipv6Domain = "cdn6.cdnss.dpdns.org"

	// 全局优化状态
	optimizationState = make(map[string]AlgorithmParams)
)

var blacklist = map[string]bool{
	"172.64.229.18": true,
	"172.64.229.17": true,
}

// ------------------- 基础工具函数 -------------------
func loadConfig(path string) ([]CIDRConfig, error) {
	data, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, err
	}
	var listFile []CIDRConfigFile
	if err := json.Unmarshal(data, &listFile); err != nil {
		return nil, err
	}
	res := make([]CIDRConfig, len(listFile))
	for i, f := range listFile {
		res[i] = CIDRConfig{CIDR: f.CIDR, MaxSuccess: f.MaxSuccess, MaxDelay: f.MaxDelay, Delays: []int64{}}
	}
	return res, nil
}

func saveConfig(path string, cfgs []CIDRConfig) error {
	tmp := make([]CIDRConfigFile, len(cfgs))
	for i, c := range cfgs {
		tmp[i] = CIDRConfigFile{CIDR: c.CIDR, MaxSuccess: c.MaxSuccess, MaxDelay: c.MaxDelay}
	}
	bytes, err := json.MarshalIndent(tmp, "", "  ")
	if err != nil {
		return err
	}
	return ioutil.WriteFile(path, bytes, 0644)
}

func randomUA() string {
	platforms := []string{
		"Windows NT 10.0; Win64; x64",
		"Macintosh; Intel Mac OS X 10_15_7",
		"X11; Linux x86_64",
	}
	platform := platforms[rand.Intn(len(platforms))]

	chromeVersion := 110 + rand.Intn(20)
	webkitVersion := 537 + rand.Intn(10)

	return fmt.Sprintf(
		"Mozilla/5.0 (%s) AppleWebKit/%d.36 (KHTML, like Gecko) Chrome/%d.0.0.0 Safari/%d.36",
		platform, webkitVersion, chromeVersion, webkitVersion,
	)
}

func inc(ip net.IP) {
	for j := len(ip) - 1; j >= 0; j-- {
		ip[j]++
		if ip[j] != 0 {
			break
		}
	}
}

// ------------------- 机器学习增强工具函数 -------------------
// 提取特征向量 - 用于参数优化
func extractFeatures(allHistory []HistoryEntry, cidr string) []float64 {
	var features []float64

	// 提取该CIDR的所有历史数据
	var cidrHistory []HistoryEntry
	for _, h := range allHistory {
		if h.CIDR == cidr {
			cidrHistory = append(cidrHistory, h)
		}
	}

	if len(cidrHistory) == 0 {
		return make([]float64, 10) // 返回零向量
	}

	// 查找对应的 CIDRConfig
	var cfg CIDRConfig
	for _, c := range cidrRanges {
		if c.CIDR == cidr {
			cfg = c
			break
		}
	}

	// 1. 成功率特征
	successRates := make([]float64, len(cidrHistory))
	for i, h := range cidrHistory {
		successRates[i] = float64(len(h.Delays)) / float64(cfg.MaxSuccess)
	}

	// 2. 延迟特征
	allDelays := []float64{}
	for _, h := range cidrHistory {
		for _, d := range h.Delays {
			allDelays = append(allDelays, float64(d))
		}
	}

	if len(allDelays) == 0 {
		return make([]float64, 10)
	}

	// 计算基本统计特征
	avgDelay := stat.Mean(allDelays, nil)
	stdDelay := stat.StdDev(allDelays, nil)

	// 3. 趋势特征 (使用线性回归)
	x := make([]float64, len(cidrHistory))
	y := make([]float64, len(cidrHistory))
	for i := range cidrHistory {
		x[i] = float64(i)
		// 使用该天的平均延迟
		sum := 0.0
		for _, d := range cidrHistory[i].Delays {
			sum += float64(d)
		}
		if len(cidrHistory[i].Delays) > 0 {
			y[i] = sum / float64(len(cidrHistory[i].Delays))
		}
	}

	// 简单线性回归 y = mx + b
	n := float64(len(x)) // 修复：将n转换为float64
	sumX, sumY, sumXY, sumX2 := 0.0, 0.0, 0.0, 0.0
	for i := 0; i < len(x); i++ {
		sumX += x[i]
		sumY += y[i]
		sumXY += x[i] * y[i]
		sumX2 += x[i] * x[i]
	}

	denominator := n*sumX2 - sumX*sumX
	if denominator == 0 {
		return make([]float64, 10)
	}

	slope := (n*sumXY - sumX*sumY) / denominator
	intercept := (sumY - slope*sumX) / n

	// 计算R² (拟合优度)
	sumResiduals := 0.0
	sumTotal := 0.0
	yMean := sumY / float64(len(x))
	for i := 0; i < len(x); i++ {
		predicted := slope*x[i] + intercept
		sumResiduals += math.Pow(y[i]-predicted, 2)
		sumTotal += math.Pow(y[i]-yMean, 2)
	}

	rSquared := 1.0 - (sumResiduals / sumTotal)

	// 构建特征向量
	features = append(features,
		avgDelay,                       // 平均延迟
		stdDelay,                       // 延迟标准差
		stat.Mean(successRates, nil),   // 平均成功率
		stat.StdDev(successRates, nil), // 成功率标准差
		slope,                          // 延迟趋势斜率
		rSquared,                       // 趋势置信度
		float64(len(cidrHistory)),      // 历史数据点数量
	)

	// 添加季节性特征 (简化版)
	if len(cidrHistory) >= 7 {
		// 计算最近7天的波动
		weeklyFluctuation := 0.0
		for i := 1; i < 7 && i < len(cidrHistory); i++ {
			weeklyFluctuation += math.Abs(y[len(y)-1] - y[len(y)-1-i])
		}
		features = append(features, weeklyFluctuation/6.0)
	} else {
		features = append(features, 0.0)
	}

	// 添加异常值比例
	outlierCount := 0
	threshold := avgDelay + 3*stdDelay // 3-sigma规则
	for _, d := range allDelays {
		if d > threshold {
			outlierCount++
		}
	}
	features = append(features, float64(outlierCount)/float64(len(allDelays)))

	// 添加成功率变化率
	if len(successRates) >= 2 {
		features = append(features, successRates[len(successRates)-1]-successRates[len(successRates)-2])
	} else {
		features = append(features, 0.0)
	}

	return features
}

// 计算系统状态统计 - 增强版
func computeSystemStats(allHistory []HistoryEntry, cfg CIDRConfig) SystemStats {
	var allDelays []float64
	var successRates []float64

	// 提取该CIDR的所有历史数据
	var cidrHistory []HistoryEntry
	for _, h := range allHistory {
		if h.CIDR == cfg.CIDR {
			cidrHistory = append(cidrHistory, h)
		}
	}

	if len(cidrHistory) == 0 {
		return SystemStats{}
	}

	// 计算成功率统计
	for _, h := range cidrHistory {
		successRate := float64(len(h.Delays)) / float64(cfg.MaxSuccess)
		successRates = append(successRates, successRate)

		for _, d := range h.Delays {
			allDelays = append(allDelays, float64(d))
		}
	}

	// 计算延迟统计
	avgDelay := stat.Mean(allDelays, nil)
	stdDev := stat.StdDev(allDelays, nil)

	// 计算趋势 (使用线性回归)
	x := make([]float64, len(cidrHistory))
	y := make([]float64, len(cidrHistory))
	for i, h := range cidrHistory {
		x[i] = float64(i)
		sum := 0.0
		for _, d := range h.Delays {
			sum += float64(d)
		}
		if len(h.Delays) > 0 {
			y[i] = sum / float64(len(h.Delays))
		}
	}

	// 简单线性回归
	n := float64(len(x)) // 修复：将n转换为float64
	sumX, sumY, sumXY, sumX2 := 0.0, 0.0, 0.0, 0.0
	for i := 0; i < len(x); i++ {
		sumX += x[i]
		sumY += y[i]
		sumXY += x[i] * y[i]
		sumX2 += x[i] * x[i]
	}

	denominator := n*sumX2 - sumX*sumX
	if denominator == 0 {
		return SystemStats{
			SuccessRate:       stat.Mean(successRates, nil),
			DelayAvg:          avgDelay,
			DelayStdDev:       stdDev,
			Trend:             0,
			TrendConfidence:   0,
			SeasonalAmplitude: 0,
			OutlierRatio:      0,
		}
	}

	slope := (n*sumXY - sumX*sumY) / denominator
	intercept := (sumY - slope*sumX) / n

	// 计算R² (拟合优度)
	sumResiduals := 0.0
	sumTotal := 0.0
	yMean := sumY / float64(len(x))
	for i := 0; i < len(x); i++ {
		predicted := slope*x[i] + intercept
		sumResiduals += math.Pow(y[i]-predicted, 2)
		sumTotal += math.Pow(y[i]-yMean, 2)
	}

	rSquared := 1.0 - (sumResiduals / sumTotal)

	// 计算季节性特征 (简化版)
	seasonalAmplitude := 0.0
	if len(cidrHistory) >= 7 {
		// 计算最近7天的波动
		weeklyFluctuation := 0.0
		for i := 1; i < 7 && i < len(cidrHistory); i++ {
			weeklyFluctuation += math.Abs(y[len(y)-1] - y[len(y)-1-i])
		}
		seasonalAmplitude = weeklyFluctuation / 6.0
	}

	// 计算异常值比例
	outlierCount := 0
	threshold := avgDelay + 3*stdDev // 3-sigma规则
	for _, d := range allDelays {
		if d > threshold {
			outlierCount++
		}
	}
	outlierRatio := float64(outlierCount) / float64(len(allDelays))

	return SystemStats{
		SuccessRate:       stat.Mean(successRates, nil),
		DelayAvg:          avgDelay,
		DelayStdDev:       stdDev,
		Trend:             slope,
		TrendConfidence:   rSquared,
		SeasonalAmplitude: seasonalAmplitude,
		OutlierRatio:      outlierRatio,
	}
}

// 加权移动平均
func weightedMovingAverage(values, weights []float64) float64 {
	n := len(values)
	if n == 0 || len(weights) != n {
		return 0
	}
	var sum, totalWeight float64
	for i := 0; i < n; i++ {
		sum += values[i] * weights[i]
		totalWeight += weights[i]
	}
	if totalWeight == 0 {
		return 0
	}
	return sum / totalWeight
}

// 预测下一次MaxDelay
func predictMaxDelayWithWMA(ys []float64, windowSize int) int64 {
	n := len(ys)
	if n == 0 {
		return 1000 // fallback 默认
	}
	if n < windowSize {
		windowSize = n
	}
	weights := make([]float64, windowSize)
	for i := 0; i < windowSize; i++ {
		weights[i] = float64(i + 1) // 最近权重更高
	}
	start := n - windowSize
	wma := weightedMovingAverage(ys[start:], weights)
	return int64(math.Ceil(wma))
}

// 计算每日PXX (P80)
func computeDailyPXX(allHistory []HistoryEntry, targetCIDR string) (xs, ys []float64, dates []string) {
	sort.Slice(allHistory, func(i, j int) bool {
		return allHistory[i].Date < allHistory[j].Date
	})

	// delayMap 会把同时间戳的数据聚到一起
	delayMap := make(map[string][]int64)
	for _, h := range allHistory {
		if h.CIDR != targetCIDR {
			continue
		}
		delayMap[h.Date] = append(delayMap[h.Date], h.Delays...)
	}

	var sortedTimes []string
	for t := range delayMap {
		sortedTimes = append(sortedTimes, t)
	}
	sort.Strings(sortedTimes)

	for i, t := range sortedTimes {
		ds := delayMap[t]
		sort.Slice(ds, func(a, b int) bool { return ds[a] < ds[b] })
		n := len(ds)
		idx := int(math.Ceil(0.8*float64(n))) - 1 // P80
		if idx < 0 {
			idx = 0
		}
		p80 := float64(ds[idx])

		xs = append(xs, float64(i+1))
		ys = append(ys, p80)
		dates = append(dates, t)
	}
	return
}

// 根据成功数计算百分位索引对应延迟
func computeDynamicPercentile(delays []int64, rate float64) float64 {
	if len(delays) == 0 {
		return 0
	}
	if rate < 0 {
		rate = 0
	}
	if rate > 1 {
		rate = 1
	}
	sort.Slice(delays, func(i, j int) bool { return delays[i] < delays[j] })
	idx := int(math.Ceil(rate*float64(len(delays)))) - 1
	if idx < 0 {
		idx = 0
	}
	return float64(delays[idx])
}

// 计算EWMA序列
func computeEWMA(values []float64, alpha float64) []float64 {
	if len(values) == 0 {
		return nil
	}
	result := make([]float64, len(values))
	result[0] = values[0]
	for i := 1; i < len(values); i++ {
		result[i] = alpha*values[i] + (1-alpha)*result[i-1]
	}
	return result
}

// 计算EWMA序列的斜率
func computeEWMASlope(values []float64, window int, alpha float64) float64 {
	n := len(values)
	if n < 2 || window < 1 {
		return 0
	}

	// 计算EWMA
	ewma := computeEWMA(values, alpha)

	// 计算斜率：(当前EWMA - 前window个EWMA)/window
	if n <= window {
		window = n - 1
	}
	return (ewma[n-1] - ewma[n-window-1]) / float64(window)
}

// ------------------- 强化学习参数优化 -------------------
// 模拟退火优化算法 - 寻找最优参数
func optimizeParameters(features []float64) AlgorithmParams {
	// 基础参数
	params := AlgorithmParams{
		EWMASmoothingFactor: 0.3,
		WMAPredictionWindow: 5,
		TrendThreshold:      0.3,
		StressFactorBase:    1.0,
		StressFactorExp:     2.5,
		MinChangeStep:       5.0,
		RoundStep:           5,
		FloorFactor:         0.5,
		CeilingFactor:       3.0,
	}

	// 模拟退火参数
	temperature := 100.0
	coolingRate := 0.95
	iterations := 100

	// 当前解的得分 (初始随机值)
	currentScore := evaluateParameters(features, params)

	for i := 0; i < iterations && temperature > 0.1; i++ {
		// 生成邻域解
		newParams := perturbParameters(params)

		// 评估新解
		newScore := evaluateParameters(features, newParams)

		// 接受准则
		if newScore > currentScore || math.Exp((newScore-currentScore)/temperature) > rand.Float64() {
			params = newParams
			currentScore = newScore
		}

		// 降温
		temperature *= coolingRate
	}

	return params
}

// 评估参数集的得分

// 评估参数集的得分
func evaluateParameters(features []float64, params AlgorithmParams) float64 {
	// 提取关键特征
	stdDev := features[1]
	successRate := features[2]
	trend := features[4]
	trendConfidence := features[5]
	outlierRatio := features[8]

	// 计算得分 (加权组合多个目标)
	score := 0.0

	// 1. 成功率越高越好
	score += successRate * 50.0

	// 2. 延迟波动性越低越好，增加惩罚权重
	score -= stdDev * 0.5

	// 3. 正向趋势(延迟降低)加分，增加加分权重
	if trend < 0 {
		score += math.Min(1.0, -trend*100) * trendConfidence * 30.0
	} else {
		score -= math.Min(1.0, trend*100) * trendConfidence * 30.0
	}

	// 4. 异常值越少越好
	score -= outlierRatio * 100.0

	// 5. 参数合理性惩罚 (防止极端参数)
	penalty := 0.0

	// EWMA平滑因子惩罚
	if params.EWMASmoothingFactor < 0.1 || params.EWMASmoothingFactor > 0.9 {
		penalty += math.Abs(params.EWMASmoothingFactor-0.5) * 20.0
	}

	// 窗口大小惩罚
	if params.WMAPredictionWindow < 3 || params.WMAPredictionWindow > 10 {
		penalty += math.Abs(float64(params.WMAPredictionWindow-6)) * 5.0
	}

	// 其他参数惩罚
	if params.StressFactorBase < 0.5 || params.StressFactorBase > 2.0 {
		penalty += math.Abs(params.StressFactorBase-1.2) * 10.0
	}

	if params.StressFactorExp < 1.0 || params.StressFactorExp > 4.0 {
		penalty += math.Abs(params.StressFactorExp-2.5) * 5.0
	}

	score -= penalty

	return score
}

// 扰动参数生成邻域解
func perturbParameters(params AlgorithmParams) AlgorithmParams {
	newParams := params

	// 随机扰动每个参数(概率触发)
	if rand.Float64() < 0.3 {
		newParams.EWMASmoothingFactor += (rand.Float64()*0.2 - 0.1)
		newParams.EWMASmoothingFactor = math.Max(0.1, math.Min(0.9, newParams.EWMASmoothingFactor))
	}

	if rand.Float64() < 0.3 {
		newParams.WMAPredictionWindow += rand.Intn(3) - 1
		newParams.WMAPredictionWindow = int(math.Max(3, math.Min(10, float64(newParams.WMAPredictionWindow))))
	}

	if rand.Float64() < 0.3 {
		newParams.TrendThreshold += (rand.Float64()*0.2 - 0.1)
		newParams.TrendThreshold = math.Max(0.1, math.Min(0.5, newParams.TrendThreshold))
	}

	if rand.Float64() < 0.3 {
		newParams.StressFactorBase += (rand.Float64()*0.4 - 0.2)
		newParams.StressFactorBase = math.Max(0.5, math.Min(2.0, newParams.StressFactorBase))
	}

	if rand.Float64() < 0.3 {
		newParams.StressFactorExp += (rand.Float64()*0.8 - 0.4)
		newParams.StressFactorExp = math.Max(1.0, math.Min(4.0, newParams.StressFactorExp))
	}

	if rand.Float64() < 0.3 {
		newParams.MinChangeStep += (rand.Float64()*4 - 2)
		newParams.MinChangeStep = math.Max(2.0, math.Min(15.0, newParams.MinChangeStep))
	}

	if rand.Float64() < 0.3 {
		newParams.RoundStep = int64(math.Max(5, math.Min(20, float64(newParams.RoundStep)+(rand.Float64()*10-5))))
		newParams.RoundStep = (newParams.RoundStep / 5) * 5 // 确保是5的倍数
	}

	if rand.Float64() < 0.3 {
		newParams.FloorFactor += (rand.Float64()*0.2 - 0.1)
		newParams.FloorFactor = math.Max(0.3, math.Min(0.8, newParams.FloorFactor))
	}

	if rand.Float64() < 0.3 {
		newParams.CeilingFactor += (rand.Float64()*1.0 - 0.5)
		newParams.CeilingFactor = math.Max(2.0, math.Min(5.0, newParams.CeilingFactor))
	}

	return newParams
}

// 保存优化状态
func saveOptimizationState() error {
	data, err := json.MarshalIndent(optimizationState, "", "  ")
	if err != nil {
		return err
	}
	return ioutil.WriteFile("optimization_state.json", data, 0644)
}

// 加载优化状态
func loadOptimizationState() error {
	data, err := ioutil.ReadFile("optimization_state.json")
	if err != nil {
		if os.IsNotExist(err) {
			return nil // 文件不存在，返回nil
		}
		return err
	}
	return json.Unmarshal(data, &optimizationState)
}

// ------------------- Cloudflare 相关 -------------------
func getZoneID(api *cloudflare.API, domain string) (string, error) {
	zones, err := api.ListZones(context.Background())
	if err != nil {
		return "", err
	}
	for _, z := range zones {
		if z.Name == domain {
			return z.ID, nil
		}
	}
	return "", fmt.Errorf("zone not found: %s", domain)
}

func clearDNSRecords(api *cloudflare.API, zone *cloudflare.ResourceContainer, name, recordType string) {
	recs, _, err := api.ListDNSRecords(context.Background(), zone, cloudflare.ListDNSRecordsParams{Type: recordType, Name: name})
	if err != nil {
		log.Printf("failed to list %s records: %v", name, err)
		return
	}
	var wg sync.WaitGroup
	for _, r := range recs {
		wg.Add(1)
		go func(id string) {
			defer wg.Done()
			api.DeleteDNSRecord(context.Background(), zone, id)
		}(r.ID)
	}
	wg.Wait()
}

// 获取指定日期的延迟数据
func getTodayDelays(history []HistoryEntry, cidr, date string) []int64 {
	for _, h := range history {
		if h.CIDR == cidr && h.Date == date {
			return h.Delays
		}
	}
	return nil
}

// ------------------- 测试连接逻辑 -------------------
func testConnection(ip string, seq int64,
	cfg *CIDRConfig,
	client *http.Client, api *cloudflare.API, zone *cloudflare.ResourceContainer,
	mu *sync.Mutex, totalDelay *int64, successCount *int64, minDelay *int64,
	counter *int64, wg *sync.WaitGroup,
) {
	defer wg.Done()
	ctx, cancel := context.WithTimeout(context.Background(), time.Duration(cfg.MaxDelay)*time.Millisecond)
	defer cancel()

	url := "https://" + ip
	if net.ParseIP(ip).To4() == nil {
		url = "https://[" + ip + "]"
	}
	req, _ := http.NewRequestWithContext(ctx, "GET", url, nil)
	req.Host = host
	req.Close = true
	req.Header.Set("User-Agent", randomUA())
	req = req.WithContext(httptrace.WithClientTrace(ctx, &httptrace.ClientTrace{GotFirstResponseByte: func() {}}))

	start := time.Now()
	resp, err := client.Do(req)
	if err != nil {
		return
	}
	defer resp.Body.Close()

	dur := time.Since(start).Milliseconds()
	if dur > cfg.MaxDelay {
		return
	}

	mu.Lock()
	*totalDelay += dur
	*successCount++
	if dur < *minDelay {
		*minDelay = dur
	}
	*counter++
	cfg.Delays = append(cfg.Delays, dur)
	if *counter > cfg.MaxSuccess {
		mu.Unlock()
		return
	}
	mu.Unlock()

	fmt.Printf("[%d] %s => %dms\n", seq, ip, dur)
	recType, name := "A", youxuanomain
	if net.ParseIP(ip).To4() == nil {
		recType, name = "AAAA", ipv6Domain
	}
	api.CreateDNSRecord(context.Background(), zone, cloudflare.CreateDNSRecordParams{
		Type:    recType,
		Name:    name,
		Content: ip,
		TTL:     60,
	})
}

// ------------------- 主函数 -------------------
func main() {
	rand.Seed(time.Now().UnixNano())

	// 1. 加载 config
	var err error
	cidrRanges, err = loadConfig("config.json")
	if err != nil {
		log.Fatalf("读取 config.json 失败: %v", err)
	}
	for i := range cidrRanges {
		cidrRanges[i].Delays = []int64{}
	}

	// 2. 加载优化状态
	if err := loadOptimizationState(); err != nil {
		log.Printf("加载优化状态失败: %v", err)
	}

	api, err := cloudflare.NewWithAPIToken(apiToken)
	if err != nil {
		log.Fatal(err)
	}
	zoneID, err := getZoneID(api, domain)
	if err != nil {
		log.Fatal(err)
	}
	zone := cloudflare.ZoneIdentifier(zoneID)

	// 3. 清除旧 DNS 记录
	clearDNSRecords(api, zone, youxuanomain, "A")
	fmt.Println("旧 ipv4 记录删除完成！")
	clearDNSRecords(api, zone, ipv6Domain, "AAAA")
	fmt.Println("旧 ipv6 记录删除完成！")

	// 4. 扫描阶段
	sem := make(chan struct{}, maxConcurrent)
	var wg sync.WaitGroup
	var mu sync.Mutex
	var totalDelay, successCount, totalCount, minDelay int64
	minDelay = math.MaxInt64

	start := time.Now()
	fmt.Println("开始扫描...")

	for i := range cidrRanges {
		cfg := &cidrRanges[i]
		ip, ipNet, err := net.ParseCIDR(cfg.CIDR)
		if err != nil {
			continue
		}
		var successCounter int64

		tlsCfg := &tls.Config{
			ServerName:         host,
			InsecureSkipVerify: true,
			MinVersion:         tls.VersionTLS13,
			MaxVersion:         tls.VersionTLS13,
		}
		transport := &http.Transport{TLSClientConfig: tlsCfg, DisableKeepAlives: true, MaxIdleConns: 0, IdleConnTimeout: 10 * time.Millisecond}
		client := &http.Client{Timeout: time.Duration(cfg.MaxDelay) * time.Millisecond, Transport: transport}

		for ; ipNet.Contains(ip); inc(ip) {
			ipStr := ip.String()
			if blacklist[ipStr] {
				continue
			}
			mu.Lock()
			if successCounter >= cfg.MaxSuccess {
				mu.Unlock()
				break
			}
			totalCount++
			seq := totalCount
			mu.Unlock()

			sem <- struct{}{}
			wg.Add(1)
			go func(ip string, idx int64, cfg *CIDRConfig) {
				defer func() { <-sem }()
				testConnection(ip, idx, cfg, client, api, zone, &mu, &totalDelay, &successCount, &minDelay, &successCounter, &wg)
			}(ipStr, seq, cfg)
		}
	}
	wg.Wait()

	fmt.Println("扫描结束")
	fmt.Printf("总: %d, 成功: %d, 失败: %d\n", totalCount, successCount, totalCount-successCount)
	if successCount > 0 {
		fmt.Printf("平均: %.2fms, 最小: %dms\n", float64(totalDelay)/float64(successCount), minDelay)
	}
	fmt.Printf("耗时: %s\n", time.Since(start))

	// 5. 写入 history.json
	var allHistory []HistoryEntry
	raw, _ := ioutil.ReadFile("history.json")
	if len(raw) > 0 && string(raw) != "null" {
		_ = json.Unmarshal(raw, &allHistory)
	}
	today := time.Now().Format("2006-01-02 15:04:05")
	for _, cfg := range cidrRanges {
		if len(cfg.Delays) == 0 {
			continue
		}
		entry := HistoryEntry{Date: today, CIDR: cfg.CIDR, Delays: cfg.Delays}
		allHistory = append(allHistory, entry)
	}
	histBytes, _ := json.MarshalIndent(allHistory, "", "  ")
	_ = ioutil.WriteFile("history.json", histBytes, 0644)
	fmt.Println("已写入本次扫描结果到 history.json")

	// 6. 动态调整阈值
	for i := range cidrRanges {
		cfg := &cidrRanges[i]

		// 提取特征
		features := extractFeatures(allHistory, cfg.CIDR)

		// 使用强化学习优化参数
		params := optimizeParameters(features)

		// 保存优化状态
		optimizationState[cfg.CIDR] = params

		// 计算系统状态
		stats := computeSystemStats(allHistory, *cfg)

		// 历史数据提取
		_, ys, dates := computeDailyPXX(allHistory, cfg.CIDR)
		if len(dates) == 0 {
			continue
		}
		lastDate := dates[len(dates)-1]

		// 今日成功数
		todayDelays := getTodayDelays(allHistory, cfg.CIDR, lastDate)
		todayCount := len(todayDelays)

		// 计算成功率
		successRate := float64(todayCount) / float64(cfg.MaxSuccess)
		if successRate > 1 {
			successRate = 1
		}

		// 计算 delay(P=rate)
		dynamicP := computeDynamicPercentile(todayDelays, successRate)

		// 预测值（滑动加权）
		wma := float64(predictMaxDelayWithWMA(ys, params.WMAPredictionWindow))

		// 计算趋势
		slope := computeEWMASlope(ys, 3, params.EWMASmoothingFactor)

		// 当前阈值
		currentDelay := float64(cfg.MaxDelay)

		// 基础参考值：使用滑动加权平均
		baseDelay := wma

		// 基于成功率的动态调整因子
		var stressFactor float64
		if successRate >= 0.7 {
			stressFactor = params.StressFactorBase - 0.3*(successRate-0.7)
		} else if successRate >= 0.4 {
			stressFactor = params.StressFactorBase + 0.5*(0.4-successRate)
		} else {
			stressFactor = params.StressFactorBase + math.Exp(params.StressFactorExp*(0.4-successRate)) - 1
		}

		// 趋势增强因子
		trendFactor := 1.0
		if successRate > params.TrendThreshold && slope < 0 {
			trendFactor = 1.0 - math.Min(0.3, -slope*5)
		} else if slope > 0 {
			trendFactor = 1.0 + math.Min(0.3, slope*5)
		}

		// 计算目标阈值
		targetDelay := baseDelay * stressFactor * trendFactor

		// 平滑调整
		if math.Abs(targetDelay-currentDelay) < params.MinChangeStep {
			if targetDelay > currentDelay {
				targetDelay = currentDelay + params.MinChangeStep
			} else {
				targetDelay = currentDelay - params.MinChangeStep
			}
		}

		// 四舍五入
		newDelay := ((int64(targetDelay) + params.RoundStep/2) / params.RoundStep) * params.RoundStep

		// 限制上下限
		minFloor := int64(math.Max(50, stats.DelayAvg*params.FloorFactor))
		maxCeiling := int64(math.Min(2000, stats.DelayAvg*params.CeilingFactor))
		if newDelay < minFloor {
			newDelay = minFloor
		}
		if newDelay > maxCeiling {
			newDelay = maxCeiling
		}

		// 应用调整
		if newDelay != cfg.MaxDelay {
			fmt.Printf("[动态阈值] %s 成功率=%.2f%%, 百分位=%dms, 滑动加权=%.1fms, 趋势斜率=%.4f, 调整因子=%.3f, 趋势因子=%.3f => 旧阈值=%dms, 新阈值=%dms [优化参数: α=%.2f, 窗口=%d, 压力因子=%.2f+e^(%.2f*(0.4-r))]\n",
				cfg.CIDR, successRate*100, int64(dynamicP), wma, slope, stressFactor, trendFactor, cfg.MaxDelay, newDelay,
				params.EWMASmoothingFactor, params.WMAPredictionWindow, params.StressFactorBase, params.StressFactorExp)
			cfg.MaxDelay = newDelay
		}
	}

	// 7. 保存优化状态
	if err := saveOptimizationState(); err != nil {
		log.Printf("保存优化状态失败: %v", err)
	}

	// 8. 保存新 config.json
	if err := saveConfig("config.json", cidrRanges); err != nil {
		log.Printf("保存 config.json 失败: %v", err)
	} else {
		fmt.Println("已将新 MaxDelay 写回 config.json")
	}
}
